package sj;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOError;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.SimpleTimeZone;

public class demo3 {
    public static void main(String[] args) throws DocumentException, IOException, TransformerException, ParserConfigurationException, SAXException {
        // 得到Document
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("src/sj/demo1.xml"));
        //获取root元素
        Element root = doc.getRootElement();
        for (Iterator inBrand = root.elementIterator();inBrand.hasNext();){
            Element brand= (Element) inBrand.next();
            System.out.println(brand.attributeValue("name"));
            for (Iterator inType=brand.elementIterator();inType.hasNext();){
                Element type= (Element) inType.next();
                System.out.println(brand.attributeValue("name"));
            }
        }
        Element brand = DocumentHelper.createElement("Brand"); //添加了student元素
        // 给stuEle添加属性，名为number，值为1003
        brand.addAttribute("name", "三星");
        // 分别为stuEle添加名为name、age、sex的子元素，并为子元素设置文本内容
        Element typeElement=DocumentHelper.createElement("Type");
        typeElement.addAttribute("name","NoteX");
        brand.add(typeElement);
        root.add(brand);

        //修改
        for (Iterator it=root.elementIterator(); it.hasNext();){
            Element elm= (Element) it.next();
            String name=elm.attributeValue("name");
            if (name.equals("三星")){
                Attribute att=elm.attribute("name");
                att.setText("SAMSUNG");
            }
        }

        //删除
        for (Iterator it=root.elementIterator(); it.hasNext();){
            Element elm= (Element) it.next();
            String name=elm.attributeValue("name");
            if (name.equals("SAMSUNG")){
                root.remove(elm);
            }
        }

        // 设置保存的格式化器  1. \t，使用什么来完成缩进 2. true, 是否要添加换行
        OutputFormat format = new OutputFormat("\t", true);
        format.setTrimText(true); //去掉空白
        // 在创建Writer时，指定格式化器
        XMLWriter writer = new XMLWriter(new FileOutputStream("src/sj/demo1.xml"),format);
        writer.write(doc);


    }
}
